package com.headwind.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.headwind.entity.HwUser;
import com.headwind.repository.HwUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author : Headwind
 * @version : 1.0
 * @date : Created in 2020/8/15
 * @description : 用户实现类
 */
@Service
public class HwUserService {
    private final HwUserRepository userRepository;
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    /**
     * 加密盐前缀
     */
    private final String SALT_PREFIX = "::SpringBootLearning::";

    @Autowired
    public HwUserService(HwUserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * 查询所有用户信息
     *
     * @return 用户信息
     */
    public List<HwUser> findAllUser() {
        return userRepository.findAll();
    }

    /**
     * 保存用户博客
     *
     * @param user 用户博客实体
     * @return 保存成功 {@code true} 保存失败 {@code false}
     */
    public HwUser save(HwUser user) {
        String password = user.getPassword();
        String salt = IdUtil.simpleUUID();
        String md5Pass = SecureUtil.md5(password + SALT_PREFIX + salt);
        user.setPassword(md5Pass);
        user.setSalt(salt);
        return userRepository.save(user);
    }
}
